package com.neu.cpspgateway.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.neu.cpspgateway.pojo.User;
import com.neu.cpspgateway.service.UserService;
import com.neu.cpspgateway.util.JWTUtils;
import com.neu.cpspgateway.util.result.Result;
import com.neu.cpspgateway.util.result.ResultGenerator;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation("登录")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(@RequestParam String userName,
                        @RequestParam String password) {
        try {
            if(userService.selectIdByName(userName) != null) {
                User user = userService.login(userName, password);
                if (user != null) {
                    Map<String, String> payload = new HashMap<>();
                    payload.put("id", String.valueOf(user.getId()));
                    payload.put("name", user.getName());
                    payload.put("jobNumber", user.getJobNumber());
                    payload.put("role", user.getRole());
                    payload.put("nickname", user.getNickname());
                    payload.put("userName", user.getUserName());

                    String token = JWTUtils.getToken(payload);
                    return ResultGenerator.genSuccessResult(token);
                } else {
                    return ResultGenerator.genFailResult("密码错误");
                }
            }else {
                return ResultGenerator.genFailResult("账号不存在");
            }
        }catch (Exception e){
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @ApiOperation("验证")
    @PostMapping(value = "/verify")
    public Result verify(HttpServletRequest request){
        String token = request.getHeader("token");
        User user = new User();
        try {
            DecodedJWT verify = JWTUtils.verify(token);
            user.setId(Integer.parseInt(verify.getClaim("id").asString()));
            user.setName(verify.getClaim("name").asString());
            user.setJobNumber(verify.getClaim("jobNumber").asString());
            user.setRole(verify.getClaim("role").asString());
            user.setNickname(verify.getClaim("nickname").asString());
            user.setUserName(verify.getClaim("userName").asString());
            return ResultGenerator.genSuccessResult(user);
        } catch (Exception e){
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("请先登录");
    }
}


